import time
import threading
"""
创建进程锁
lock = threading.Lock()

lock的方法：
1、上锁  lock.acquire()
2、解锁  lock.release()
"""

ticket = 100   # 一共有100张票
lock = threading.Lock()   # 实例化一把线程锁


def man_buy_ticket():

    global ticket  # 声明ticket是全局变量，这样才能修改

    for i in range(1000):  # 线程进行购买1000次票

        # 当还有票的时候进行购买
        if ticket > 0:
            lock.acquire()  # 上锁
            print(f'{threading.current_thread().name}当前在购买{ticket}')  # 提示谁在买票，买的第几张
            # 买票
            ticket -= 1
            time.sleep(0.5)
            lock.release()  # 解锁


def main():
    # 创建线程
    t1 = threading.Thread(target=man_buy_ticket)
    t2 = threading.Thread(target=man_buy_ticket)
    t1.name = '善扣'
    t2.name = '启童'
    # 启动
    t1.start()
    t2.start()


if __name__ == '__main__':
    main()
